﻿using Basic.FormCollect;
using Basic.FormCollect.Model;
using Basic.FormModel.DB;
using Basic.FormModel.Form;
using Basic.FormRemoteModel;
using Basic.FormRemoteModel.PhysicalQuery.Model;
using Basic.FormRemoteModel.QueryForm.Model;
using Basic.UserFormService.Interface;
using WeDonekRpc.Client;
using WeDonekRpc.Helper;

namespace Basic.UserFormService.PhysicsTable
{
    internal class PhysicsQueryBodyService : IPhysicsQueryBodyService
    {
        private readonly ICustomFormCollect _Form;
        private readonly IPhysicsQueryBodyCollect _QueryTable;
        private readonly IPhysicalQueryCollect _PhyQuery;
        public PhysicsQueryBodyService ( ICustomFormCollect form,
            IPhysicalQueryCollect phyQuery,
            IPhysicsQueryBodyCollect table )
        {
            this._PhyQuery = phyQuery;
            this._Form = form;
            this._QueryTable = table;
        }

        public QueryFormBody Get ( long formId )
        {
            FormBaseDto form = this._Form.Get<FormBaseDto>(formId);
            if ( form.FormType != FormType.物理表单 )
            {
                throw new ErrorException("form.type.error");
            }
            DBPhysicalQueryLayout[] list = this._PhyQuery.GetsByFormId<DBPhysicalQueryLayout>(formId);
            QuerySearchBody search = new QuerySearchBody
            {
                Layout = form.Layout,
            };
            if ( ( FormLayoutType.左 & form.Layout ) == FormLayoutType.左 )
            {
                search.Left = list.ConvertFind<DBPhysicalQueryLayout, PhysicalQueryDto>(a => a.Location == LayoutLocation.左边);
            }
            if ( ( FormLayoutType.搜索栏 & form.Layout ) == FormLayoutType.搜索栏 )
            {
                search.Search = list.ConvertMap<DBPhysicalQueryLayout, PhysicalQueryDto>(a => a.Location == LayoutLocation.搜索栏 && a.IsMoreFilter == false);
                search.Filter = list.ConvertMap<DBPhysicalQueryLayout, PhysicalQueryDto>(a => a.Location == LayoutLocation.搜索栏 && a.IsMoreFilter);
            }
            PhysicsFormBody body = this._QueryTable.Get(formId);
            return new QueryFormBody
            {
                FormName = form.FormName,
                Table = body.Main.GetQueryTable(),
                Search = search
            };
        }
    }
}
